package com.lei.datastructure.queue;

import java.util.Arrays;

/**
 * @Author LeiXiaoLei
 * @Date 2022/7/19 11:12
 * @Version 1.0
 */
public class LoopQueue<E> implements Queue<E> {
    private E[] data;
    private int front, tail;

    private int size;

    public LoopQueue(int capacity) {
        this.data = (E[]) new Object[capacity + 1];
    }

    public LoopQueue() {
        this(10);
    }

    @Override
    public void enqueue(E e) {
        if ((tail + 1) % data.length == front) resize(getCapacity() * 2);
        data[tail] = e;
        tail = (tail + 1) % data.length;
        ++size;
    }

    @Override
    public E dequeue() {
        if (isEmpty())
            throw new IllegalArgumentException("Cannot dequeue from an empty queue.");
        E res = data[front];
        data[front] = null;
        front = ++front % data.length;
        --size;
        if (getSize() == getCapacity() / 4 && getCapacity() / 2 != 0)
            resize(getCapacity() / 2);
        return res;
    }

    @Override
    public E getFront() {
        return data[front];
    }

    @Override
    public int getSize() {
//        int size = 0;
//        if (tail < front) {
//            for (int i = front; i < data.length; i++) {
//                ++size;
//            }
//            for (int i = 0; i <= tail; i++) {
//                ++size;
//            }
//        }
//        if (tail > front) {
//            for (int i = front; i <= tail; i++) {
//                ++size;
//            }
//        }
//        return size;
        return this.size;
    }

    @Override
    public boolean isEmpty() {
        return tail == front;
    }

    public int getCapacity() {
        return data.length - 1;
    }

    private void resize(int newCapacity) {
        E[] newData = (E[]) new Object[newCapacity + 1];
        for (int i = 0; i < size; i++) {
            newData[i] = data[(i + front) % data.length];
        }
        data = newData;
        front = 0;
        tail = size;
        System.out.println("");
    }

    @Override
    public String toString() {
        return "LoopQueue{" +
                "data=" + Arrays.toString(data) +
                ", front=" + front +
                ", tail=" + tail +
                ",size=" + size +
                ",capacity=" + getCapacity() +
                '}';
    }
}
